
package com.csailing4cloud.csailing.auth.config;

import com.csailing4cloud.csailing.common.seicurity.component.CsailingWebResponseExceptionTranslator;
import com.csailing4cloud.csailing.common.seicurity.constants.SecurityConstants;
import com.csailing4cloud.csailing.common.seicurity.entity.CsailingUser;
import com.csailing4cloud.csailing.common.seicurity.service.CsailingClientDetailService;
import com.csailing4cloud.csailing.common.seicurity.service.CsailingUserDetailsService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dyh
 * 认证服务器配置
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	private final DataSource dataSource;
	private final CsailingUserDetailsService csailingUserDetailsService;
	private final AuthenticationManager authenticationManagerBean;
	private final RedisConnectionFactory redisConnectionFactory;

	@Override
	@SneakyThrows
	public void configure(ClientDetailsServiceConfigurer clients) {
		CsailingClientDetailService clientDetailsService = new CsailingClientDetailService(dataSource);
		clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
		clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
		clients.withClientDetails(clientDetailsService);
	}


	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
		oauthServer
				.allowFormAuthenticationForClients()
				.checkTokenAccess("isAuthenticated()");
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
		endpoints
				.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
				.tokenStore(tokenStore())
				.tokenEnhancer(tokenEnhancer())
				.userDetailsService(csailingUserDetailsService)
				.authenticationManager(authenticationManagerBean)
				.reuseRefreshTokens(false)
				.exceptionTranslator(new CsailingWebResponseExceptionTranslator())
		;
		// ## 默认token过期时间为12小时，以下代码配置token过期时间为100秒
//		DefaultTokenServices tokenServices = (DefaultTokenServices)endpoints.getDefaultAuthorizationServerTokenServices();
//		tokenServices.setTokenStore(tokenStore());
//		tokenServices.setSupportRefreshToken(true);
//		tokenServices.setAccessTokenValiditySeconds(100);
//		tokenServices.setClientDetailsService(clientDetailsService);
//		tokenServices.setTokenEnhancer(tokenEnhancer());
//		addUserDetailsService(tokenServices,csailingUserDetailsService);
//		endpoints.tokenServices(tokenServices);
	}

//	private void addUserDetailsService(DefaultTokenServices tokenServices, UserDetailsService userDetailsService) {
//		if (userDetailsService != null) {
//			PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
//			provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken>(
//					userDetailsService));
//			tokenServices
//					.setAuthenticationManager(new ProviderManager(Arrays.<AuthenticationProvider> asList(provider)));
//		}
//	}


	@Bean
	public TokenStore tokenStore() {
		RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
		tokenStore.setPrefix(SecurityConstants.CSAILING_PREFIX + SecurityConstants.OAUTH_PREFIX);
		return tokenStore;
	}

	/**
	 * token增强，客户端模式不增强。
	 *
	 * @return TokenEnhancer
	 */
	@Bean
	public TokenEnhancer tokenEnhancer() {
		return new TokenEnhancer() {
			@Override
			public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
				if (SecurityConstants.CLIENT_CREDENTIALS
						.equals(authentication.getOAuth2Request().getGrantType())) {
					return accessToken;
				}

				final Map<String, Object> additionalInfo = new HashMap<>(8);
				CsailingUser csailUser = (CsailingUser) authentication.getUserAuthentication().getPrincipal();
				additionalInfo.put("user_id", csailUser.getId());
				additionalInfo.put("username", csailUser.getUsername());
				additionalInfo.put("license", SecurityConstants.CSAILING_LICENSE);
				((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
				return accessToken;
			}
		};
	}


}
